<?php

namespace Pm\Controllers;

use Helpers\Main;
use Helpers\Assets;
use Admin\Models\pm\XhpmProduct;
use Modules\Power;
use Services\App;
use Admin\Models\track\XhtrackTask;

class ProductController extends ControllerBase
{
    private static $productTypes = [
        1 => '学生',
        2 => '教师',
        3 => '家长',
        4 => '通用',
        5 => '服务端',
        6 => 'Web端',
    ];

    private static $bArchived = [
        0 => '未归档' ,
        1 => '已归档',
    ];

    /**
     * 产品列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    public function indexAction()
    {
        if (!Power::exist('Bpm_Product')) {
            return $this->sendViewError('无产品管理权限');
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        $this->view->pick('product/productList');
        Assets::importJs('js/product/productList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->setVars([
            'productAdd' => Power::exist('Bpm_Product_Add'),
            'productEdit' => Power::exist('Bpm_Product_Edit'),
            'productDel' => Power::exist('Bpm_Product_Del'),
            'productArchive' => Power::exist('Bpm_Product_Archive'),
            'testCase' => Power::exist('Bpm_Product_TestCase'),
            'bArchived' => self::$bArchived,
            'productTypes' => self::$productTypes,
        ]);
    }

    /**
     * 获取产品列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    public function getProductAction()
    {
        try {
            if (!Power::exist('Bpm_Product')) {
                return $this->sendErrorResponse(500, '无产品管理权限');
            }
            $type = $this->request->getPost('type', 'int'); //根据状态太筛选
            $bArchived = $this->request->getPost('bArchived', 'int'); //根据归档状态筛选
            $productName = $this->request->getPost('productName', 'string'); //根据项目状态太筛选
            $condition = " bDelete = 0";
            $condition .= isset($bArchived)&&$bArchived != ''&&in_array($bArchived, [0,1]) ? " AND bArchived = $bArchived" : '';
            $condition .= $type ? " AND iType = $type" : '';
            $condition .= $productName ? " AND (sName LIKE '%$productName%' OR sCode LIKE '%$productName%' OR sAndroPackage LIKE '%$productName%' OR sAndroProject LIKE '%$productName%' OR sIosPackage LIKE '%$productName%' OR sIosEntPackage LIKE '%$productName%' OR sServiceUrl LIKE '%$productName%' OR sDocUrl LIKE '%$productName%')" : '';
            $builder = $this->modelsManager->createBuilder()
                ->addFrom('Admin\Models\pm\XhpmProduct')
                ->where($condition)
                ->orderBy("sCode");
            $data = Main::runBuilderPaginator($builder, true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 新建/编辑 产品表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    public function productFormAction()
    {
        $iId = $this->request->getQuery('iId', 'int');
        if ($iId) {
            if (!Power::exist('Bpm_Product_Edit')) {
                return $this->sendViewError('无编辑产品权限');
            }
        } else {
            if (!Power::exist('Bpm_Product_Add')) {
                return $this->sendViewError('无新增产品权限');
            }
        }
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/product/productForm.js');
        $this->view->pick('product/productForm');
        $this->view->setVars([
            'iId' => $iId,
            'productTypes' => self::$productTypes,
        ]);
    }

    /**
     * 新建/编辑项目/版本/模块
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    public function saveProductAction()
    {
        $iId = $this->request->getPost('iId', 'int');
        //项目创建人id && name
        try {
            $this->db->begin();  //开启事务
            if ($iId) {
                if (!Power::exist('Bpm_Product_Edit')) {
                    return $this->sendErrorResponse(500, '无编辑产品权限');
                }
                $product = XhpmProduct::findFirst($iId);
                if (!$product) {
                    return $this->sendErrorResponse(400, '产品不存在！');
                }
            } else {
                if (!Power::exist('Bpm_Product_Add')) {
                    return $this->sendErrorResponse(500, '无新增产品权限');
                };
                $product = new XhpmProduct();
            }
            $product->assign($this->request->getPost());
            $result = $product->save();
            if (!$result) {
                $this->db->rollback();
                return $iId ? $this->sendErrorResponse(500, '编辑产品失败') : $this->sendErrorResponse(500, '创建产品失败');
            }
            $this->db->commit();
            return $iId ? $this->sendSuccessResponse('编辑产品成功') : $this->sendSuccessResponse('创建产品成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iId ?
                $this->sendErrorResponse(500, '编辑产品失败', $exception->getMessage()) :
                $this->sendErrorResponse(500, '创建产品失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的产品
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */

    public function getProductInfoAction()
    {
        try {
            $iId = $this->request->getPost('iId', 'int');
            if (!$iId) {
                return $this->sendErrorResponse(400, '获取产品信息失败', '缺少参数');
            }
            $obj = XhpmProduct::findFirst($iId);
            $data = $obj ? $obj->toArray() : [];
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取产品信息失败', $exception->getMessage());
        }
    }

    /**
     * 删除项目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180504
     */
    public function delProductByIdAction()
    {
        if (!Power::exist('Bpm_Product_Del')) {
            return $this->sendErrorResponse(500, '无删除产品权限');
        }
        $iId = $this->request->getPost('iId', 'int');
        try {
            $this->db->begin();
            $productObj = XhpmProduct::findFirst([
                'conditions' => "bDelete = 0 AND iId = $iId"
            ]);
            if (!$productObj) {
                return $this->sendErrorResponse(400, '产品不存在');
            }
            $productObj->bDelete = 1;
            $re = $productObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 获取应用列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180516
     * modify by zqk 20181016
     */
    public function getProductsAction()
    {   
		$productName = $this->request->getPost('productName', 'string', '');
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns('iId,sName,iType')
                ->addFrom('Admin\Models\pm\XhpmProduct')
                ->where('bDelete = 0');
            if (!empty($productName)) {
                $builder->andWhere("sName like '%{$productName}%'");
            }
            $apps =  $builder->getQuery()->execute()->toArray();
            $productTypes = self::$productTypes;
            foreach ($apps as $k => $app) {
                $apps[$k]['iId'] = $app['iId'];
                $apps[$k]['sName'] = $app['sName'] . '(' . $productTypes[$app['iType']] . ')';
            }
            return $this->sendJsonResponse($apps);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取应用失败', $exception->getMessage());
        }
    }


    /* ***********************************逻辑分离代码需要补充*********************************************/
    /**
     * 归档product
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20190128
     */
    public function archiveProductByIdAction()
    {
        if (!Power::exist('Bpm_Product_Archive')) {
            return $this->sendErrorResponse(500, '权限不足', '无归档权限');
        }
        $iId = $this->request->getPost('iId', 'int');
        try {
            $this->db->begin();
            $product = XhpmProduct::findFirst([
                'conditions' => "bDelete = 0 AND iId = $iId"
            ]);
            if (empty($product)) {
                return $this->sendErrorResponse(400, '参数错误', '该产品不存在');
            }
            if ($product->bArchived == 1) {
                $this->db->rollback();
                return $this->sendErrorResponse(400, '产品已归档');
            } else {
                $product->bArchived = 1;
            }
            $res = $product->save();
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '操作失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

}

